package com.sky.demo.fragment;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sky.demo.R;

import java.util.Random;

public class Three extends Fragment {
    public AnimationDrawable ani_start;
    public View http_loadView;
    public TextView tv;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    stopAnimation();
                    int math1 = (int) (Math.random() * 10);
                    handler.sendEmptyMessageDelayed(math1, 5000);
                    break;
                case 1:
                    ani_start.setOneShot(false);
                    ani_start.stop();
                    if (!ani_start.isRunning())
                        ani_start.start();
                    int math2 = (int) (Math.random() * 10);
                    handler.sendEmptyMessageDelayed(math2, 10000);
                    break;
                default:
                    int math3 = (int) (Math.random() * 10);
                    handler.sendEmptyMessageDelayed(math3, 100);
                    break;
            }

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        http_loadView = inflater.inflate(R.layout.fragment_three, null);
        ImageView start = (ImageView) http_loadView.findViewById(R.id.start);
        tv = (TextView) http_loadView.findViewById(R.id.text);
        ani_start = (AnimationDrawable) start.getBackground();
        ani_start.setOneShot(false);
        ani_start.start();
        new Animator().run();
        return http_loadView;
    }

    public void stopAnimation() {
        if (ani_start.isRunning()) {
            ani_start.setOneShot(true);
        }
    }

    class Animator implements Runnable {

        @Override
        public void run() {

//            while (!Thread.currentThread().isInterrupted()) {
            Message message = new Message();
            message.what = 0;
            handler.sendMessage(message);
            try {
                Thread.sleep(00);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                e.printStackTrace();
            }
//            }
        }
    }
}
